<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert title="注意：只允许为第三级设置相关参数!" type="warning" show-icon :closable="false"></el-alert>
      <!-- 级联选择框区域 -->
      <el-row class="elRow">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择框 -->
          <!-- options:要渲染的数据 :props:配置级联选择框 @change时刻监听级联选择器 -->
          <el-cascader
            v-model="CascaderList"
            :options="cateList"
            :props="setCascader"
            @change="cateListChange"
            clearable
            change-on-select
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnDisable" @click="addDialogVisible = true">添加参数</el-button>
          <!-- 渲染动态参数表格 -->
          <el-table :data="paramsList" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" class="elTag" closable @close="closeTagBtn(scope.row,i)">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editsForm(scope.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteForm(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtnDisable" @click="addDialogVisible = true">添加属性</el-button>
          <!-- 渲染静态属性表格 -->
          <el-table :data="staticProperty" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" class="elTag" closable @close="closeTagBtn(scope.row,i)">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editsForm(scope.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteForm(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加动态参数或静态属性对话框 -->
    <el-dialog
      :title="activeName==='many'?'动态参数':'静态属性'"
      :visible.sync="addDialogVisible"
      width="60%"
      @close="closeAddForm"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addRuleFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="activeName==='many'?'动态参数':'静态属性'" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑动态参数或静态属性对话框 -->
    <el-dialog
      :title="activeName==='many'?'动态参数':'静态属性'"
      :visible.sync="editDialogVisible"
      width="60%"
      @close="closeEditForm"
    >
      <el-form
        :model="editForm"
        :rules="editRules"
        ref="editRuleFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="activeName==='many'?'动态参数':'静态属性'" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 获取的商品分类列表
      cateList: [],
      // 配置级联选择框
      setCascader: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择框双向绑定的数组
      CascaderList: [],
      // 默认展示动态参数
      activeName: 'many',
      // 获取到的动态参数
      paramsList: [],
      // 获取到静态属性
      staticProperty: [],
      // 添加动态参数参数
      addForm: {
        attr_name: ''
      },
      // 显示与隐藏添加动态参数对话框
      addDialogVisible: false,
      // 添加动态参数表单验证
      addRules: {
        attr_name: [
          { required: true, message: '请输入角色名', trigger: 'blur' }
        ]
      },
      // 根据id获取动态参数或静态属性
      editForm: [],
      // 显示与隐藏编辑对话框
      editDialogVisible: false,
      // 提交编辑验证
      editRules: {
        attr_name: [
          { required: true, message: '请输入角色名', trigger: 'blur' }
        ]
      },
      // 获取分类id
      id: 0
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.axios.get('categories')
      if (res.meta.status !== 200) return this.msg.error('获取商品分类列表失败')
      this.cateList = res.data
    },
    // 获取级联选择框最新的数据
    cateListChange() {
      this.getParamsData()
    },
    // 点击修改了tabs，会触发这个函数
    handleTabsClick() {
      this.getParamsData()
    },
    // 级联选择框修改，tags修改多可以触发获取参数函数
    async getParamsData() {
      if (this.CascaderList.length !== 3) {
        this.CascaderList = []
        this.paramsList = []
        this.staticProperty = []
      }
      this.id = this.CascaderList[this.CascaderList.length - 1]
      // 获取参数
      const { data: res } = await this.axios.get(`categories/${this.id}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.msg.error('获取参数失败')

      // 把attr_vals值使用split方法分隔成数组
      res.data.forEach(item => {
        if (item.attr_vals) {
          item.attr_vals = item.attr_vals.split(' ')
        } else {
          item.attr_vals = []
        }
        // 让每行的这个内容互不影响
        item.inputVisible = false
        item.inputValue = ''
      })
      // 判断获取的是动态参数还是静态属性
      if (this.activeName === 'many') {
        this.paramsList = res.data
      } else {
        this.staticProperty = res.data
      }
    },
    // 关闭添加对话框重置表单
    closeAddForm() {
      this.$refs.addRuleFormRef.resetFields()
    },
    // 点击添加动态参数或静态属性提交表单预验证
    submitForm() {
      this.$refs.addRuleFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.axios.post(`categories/${this.id}/attributes`, { attr_name: this.addForm.attr_name, attr_sel: this.activeName })
          if (res.meta.status !== 201) return this.msg.error('添加失败')
          this.msg('添加成功')
          this.addDialogVisible = false
          this.getParamsData()
        }
      })
    },
    // 关闭编辑对话框进行表单重置
    closeEditForm() {
      this.$refs.editRuleFormRef.resetFields()
    },
    // 编辑动态参数或静态属性
    async editsForm(scope) {
      const { data: res } = await this.axios.get(`categories/${this.id}/attributes/${scope.attr_id}`)
      if (res.meta.status !== 200) return this.msg.error('获取数据失败')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 点击提交编辑后的动态参数或者静态属性
    submitEditForm() {
      this.$refs.editRuleFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.axios.put(`categories/${this.id}/attributes/` + this.editForm.attr_id, { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
          if (res.meta.status !== 200) return this.msg.error('编辑失败')
          this.msg('编辑成功')
          this.getParamsData()
          this.editDialogVisible = false
        }
      })
    },
    // 删除动态参数或静态属性
    async deleteForm(attrId) {
      // this.cof返回的是一个Promise对象
      const result = await this.cof('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 捕捉错误并且返回这个错误
      // 点击取消返回一个cancel字符串
      // 点击确认返回一个confirm字符串
      if (result !== 'confirm') {
        return this.msg('你取消了删除')
      }
      const { data: res } = await this.axios.delete(`categories/${this.id}/attributes/${attrId.attr_id}`)
      if (res.meta.status !== 200) return this.msg.error('删除失败')
      this.msg('删除成功')
      this.getParamsData()
    },
    // enter键弹起或者失去焦点都会触发
    handleInputConfirm(row) {
      // 判断数据是否合法
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
      } else {
        // 数据合法进行下面操作
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false
        this.submitAttrVals(row)
      }
    },
    // 点击删除attr_vals值
    closeTagBtn(row, i) {
      row.attr_vals.splice(i, 1)
      this.submitAttrVals(row)
    },
    // 修改，删除，提交新的attr_vals值
    async submitAttrVals(row) {
      const { data: res } = await this.axios.put(`categories/${this.id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.msg.error('更新失败')
      this.msg('更新成功')
      this.getParamsData()
    },
    // 点击从按钮变为文本框
    showInput(row) {
      row.inputVisible = true
      // $nextTick方法的作用：就是当页面上元素全部被渲染完毕之后，才会执行回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  computed: {
    // 是否禁用添加参数或属性按钮
    isBtnDisable() {
      if (this.CascaderList.length !== 3) {
        return true
      } else {
        return false
      }
    }
  }
}
</script>

<style scoped lang="less">
  .elRow {
    margin: 15px 0;
  }
  .elTag {
    margin-right: 15px;
  }
  .input-new-tag {
    width: 150px;
  }
</style>
